package com.youdianda.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youdianda.dto.RolePageQueryDTO;
import com.youdianda.dto.RoleUpdateDTO;
import com.youdianda.entity.SysMenu;
import com.youdianda.entity.SysRole;
import com.youdianda.entity.SysUser;
import com.youdianda.mapper.SysMenuMapper;
import com.youdianda.mapper.SysRoleMapper;
import com.youdianda.mapper.SysRoleMenuMapper;
import com.youdianda.mapper.SysUserMapper;
import com.youdianda.result.Result;
import com.youdianda.service.ISysMenuService;
import com.youdianda.service.ISysRoleService;
import com.youdianda.vo.*;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author mosen
 * @since 2023-05-15
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private ISysMenuService iSysMenuService;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**角色列表分页*/
    @Override
    public RolePageQueryVO listRole(RolePageQueryDTO rolePageQueryDTO) {
        String name  = rolePageQueryDTO.getName();
        RolePageQueryVO rolePageQueryVO = new RolePageQueryVO();
        Integer count = sysRoleMapper.getRoleCount(name);
        Integer totalPages;
        if (count % rolePageQueryDTO.getLimit()>0){
            totalPages = count / rolePageQueryDTO.getLimit();
            totalPages+=1;
        }else {
            totalPages = count / rolePageQueryDTO.getLimit();
        }
        rolePageQueryVO.setCurrentPage(rolePageQueryDTO.getPage());
        rolePageQueryVO.setPageSize(rolePageQueryDTO.getLimit());
        rolePageQueryVO.setCount(count);
        rolePageQueryVO.setTotalPages(totalPages);

        Integer start = (rolePageQueryDTO.getPage()-1) * rolePageQueryDTO.getLimit();
        List<SysRole> roleList = sysRoleMapper.getRolePageByName(name,start,rolePageQueryDTO.getLimit());

        List<RoleQueryVO> roleQueryVOList = new ArrayList<>();
        for (SysRole sysRole : roleList) {
            RoleQueryVO roleQueryVO = new RoleQueryVO();
            BeanUtils.copyProperties(sysRole,roleQueryVO);
            roleQueryVO.setCreate_date(sysRole.getCreateDate());
            roleQueryVO.setUpdate_date(sysRole.getUpdateDate());
            roleQueryVO.setDel_flag(sysRole.getDelFlag());
            roleQueryVO.setDefault_data(sysRole.getDefaultData());
            roleQueryVO.setRole_id(sysRole.getId());
            List<String> roleMenuList=sysRoleMenuMapper.getMenuIdByRoleId(sysRole.getId());
            String roleMenus = Strings.join(roleMenuList, ',');
            roleQueryVO.setRole_menus(roleMenus);
            roleQueryVOList.add(roleQueryVO);
        }
        rolePageQueryVO.setData(roleQueryVOList);
        return rolePageQueryVO;
    }

    /**角色列表全部*/
    @Override
    public Result<List<RoleVO>> listAllRole() {
        List<SysRole> roleList = sysRoleMapper.getAllRole();
        List<RoleVO> roleVOList = new ArrayList<>();
        for (SysRole sysRole : roleList) {
            RoleVO roleVO = new RoleVO();
            BeanUtils.copyProperties(sysRole,roleVO);
            roleVO.setCreate_date(sysRole.getCreateDate());
            roleVO.setUpdate_date(sysRole.getUpdateDate());
            roleVO.setDel_flag(sysRole.getDelFlag());
            roleVO.setDefault_data(sysRole.getDefaultData());
            roleVOList.add(roleVO);
        }
        return Result.success(roleVOList);
    }

    /**角色详情*/
    @Override
    public Result<RoleDetailsVO> getRoleById(String id) {
        SysRole sysRole = sysRoleMapper.getRoleById(id);
        log.error(sysRole.toString());
        RoleDetailsVO roleDetailsVO = new RoleDetailsVO();
        BeanUtils.copyProperties(sysRole,roleDetailsVO);
        roleDetailsVO.setCreate_date(sysRole.getCreateDate());
        roleDetailsVO.setUpdate_date(sysRole.getUpdateDate());
        roleDetailsVO.setDel_flag(sysRole.getDelFlag());
        roleDetailsVO.setDefault_data(sysRole.getDefaultData());

        List<MenuQueryVO> voList = new ArrayList<>();
        //先获取所有对应id=role_id的对应menu_id集合，为String,改为Integer设进MenuQueryVO的id中
        List<String> menuIds = sysRoleMenuMapper.getMenuIdByRoleId(id);
        List<SysMenu> sysMenuList = new ArrayList<>();
        for (String menuId : menuIds) {
            int i = Integer.parseInt(menuId);
            SysMenu menuById = sysMenuMapper.getMenuById(i);
            if (menuById.getPid()==0){
                sysMenuList.add(menuById);
            }
        }

        for (SysMenu sysMenu : sysMenuList) {
            MenuQueryVO menuQueryVO = iSysMenuService.listAllMenuById(sysMenu.getId());
            voList.add(menuQueryVO);
        }


        roleDetailsVO.setAuthList(voList);

        return Result.success(roleDetailsVO);
    }

    /**角色修改*/
    @Override
    @Transactional
    public Result updateRole(RoleUpdateDTO roleUpdateDTO) {

        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(roleUpdateDTO,sysRole);
        sysRole.setUpdateDate(LocalDateTime.now());
        sysRoleMapper.updateRole(sysRole);

        sysRoleMenuMapper.deleteByRoleId(sysRole.getId());

        sysRoleMenuMapper.add(sysRole.getId(),roleUpdateDTO.getMenuids());

        return Result.success();
    }

    /**角色添加*/
    @Override
    @Transactional
    public Result addRole(RoleUpdateDTO roleUpdateDTO) {

        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(roleUpdateDTO,sysRole);
        sysRole.setUpdateDate(LocalDateTime.now());
        sysRole.setCreateDate(LocalDateTime.now());
        sysRole.setDelFlag("0");
        sysRole.setSuperadmin(0);
        sysRole.setDefaultData("1");

        String newId = UUID.randomUUID().toString();
        sysRole.setId(newId);

        sysRoleMapper.addRole(sysRole);
        sysRoleMenuMapper.add(newId,roleUpdateDTO.getMenuids());
        return Result.success();
    }

    /**角色删除*/
    @Override
    @Transactional
    public Result deleteRole(String id) {
        //删除role表
        sysRoleMapper.deleteRoleById(id);
        //删除role_menu表对应role_id
        sysRoleMenuMapper.deleteByRoleId(id);
        //删除user表中role_id的字符串数组中含有id的，将id部分删除
        List<SysUser> userList = sysUserMapper.selectAllUser();
        for (SysUser sysUser : userList) {
            boolean flag = false;
            String roleId = sysUser.getRoleId();
            StringBuffer sb = new StringBuffer("");
            for (int i = 0; i < roleId.length(); i++) {
                if (roleId.charAt(i)!='['&&roleId.charAt(i)!=']'&&roleId.charAt(i)!='"'){
                    sb.append(roleId.charAt(i));
                }
            }

            List<String> roleIdList = Arrays.asList(sb.toString().split(",",-1));
            for (int i = roleIdList.size()-1; i >=0; i--) {
                if (roleIdList.get(i).equals(id)){
                    roleIdList.remove(i);
                    flag=true;
                }
            }
            if (flag){
                //重新拼接,放回user表中
                StringBuffer stringBuffer = new StringBuffer("");
                stringBuffer.append('[');
                for (int i = 0; i < roleIdList.size(); i++) {
                    if (i==roleIdList.size()-1){
                        stringBuffer.append('"');
                        stringBuffer.append(roleIdList.get(i));
                        stringBuffer.append('"');
                    }else {
                        stringBuffer.append('"');
                        stringBuffer.append(roleIdList.get(i));
                        stringBuffer.append('"');
                        stringBuffer.append(',');
                    }
                }
                String newRoleId = stringBuffer.toString();
                sysUser.setRoleId(newRoleId);
                sysUserMapper.updateRoleId(sysUser);
            }
        }
        return Result.success();
    }
}
